package com.rcloud.server.sealtalk.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rcloud.server.sealtalk.configuration.ProfileConfig;
import com.rcloud.server.sealtalk.constant.ErrorCode;
import com.rcloud.server.sealtalk.domain.ExpressInfo;
import com.rcloud.server.sealtalk.exception.ServiceException;
import com.rcloud.server.sealtalk.model.ExpressContent;
import com.rcloud.server.sealtalk.service.ExpressInfoService;
import com.rcloud.server.sealtalk.util.TencentMarketClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: xiuwei.nie
 * @Author: Jianlu.Yu
 * @Date: 2020/7/7
 * @Description:
 * @Copyright (c) 2020, rongcloud.cn All Rights Reserved
 */
@Service
@Slf4j
public class ExpressManager extends BaseManager {

    @Resource
    private ExpressInfoService expressInfoService;

    @Autowired
    private TencentMarketClient expressClient;

    /**
     * 快递单号识别进行查询的功能
     */
    public ExpressInfo queryExpress(Integer userId, String com, String num) throws ServiceException {
        //首先根据单号进行数据库查询
        ExpressInfo one = expressInfoService.getOne(ExpressInfo.builder().no(num).build());
        if (one == null) {
            try {
                String result = expressClient.sendExpressReq(com, num);
                log.info("快递识别的接口返回数据:" + result);
                JSONObject express = JSON.parseObject(result);
                //如果是成功的
                if ("OK".equals(express.get("code"))) {
                    ExpressInfo expressInfo = new ExpressInfo();
                    //判断快递的状态进行 数据库的存储 3：签收 或者 6退件签收 状态进行存储  下次优先库里查询
                    if ("3".equals(express.get("state")) || "6".equals(express.get("state"))) {
                        expressInfo.setNo(express.getString("no"));
                        expressInfo.setType(express.getString("type"));
                        expressInfo.setList(express.getString("list"));
                        expressInfo.setState(express.getString("state"));
                        expressInfo.setName(express.getString("name"));
                        expressInfo.setSite(express.getString("site"));
                        expressInfo.setPhone(express.getString("phone"));
                        expressInfo.setCourier(express.getString("courier"));
                        expressInfo.setCourierPhone(express.getString("courierPhone"));
                        expressInfo.setUpdateTime(express.getString("updateTime"));
                        expressInfo.setTakeTime(express.getString("takeTime"));
                        expressInfo.setLogo(express.getString("logo"));
                        expressInfo.setCreateBy(userId);
                        expressInfo.setCreateTime(new Date());
                        expressInfoService.save(expressInfo);
                    }
                    JSONArray objects = express.getJSONArray("list");
                    List<ExpressContent> expressContents = objects.toJavaList(ExpressContent.class);
                    expressInfo.setDataArray(expressContents);
                    return expressInfo;
                } else {
                    throw new ServiceException(ErrorCode.EXPRESS_QUERY_ERROR);
                }
            } catch (Exception e) {
                if (e instanceof ServiceException) {
                    throw new ServiceException(ErrorCode.EXPRESS_QUERY_ERROR);
                } else {
                    log.info("调用接口ExpressManager出现错误：" + e);
                    e.printStackTrace();
                    return ExpressInfo.builder().build();
                }
            }
        } else {
            JSONArray objects = JSONArray.parseArray(one.getList());
            List<ExpressContent> expressContents = objects.toJavaList(ExpressContent.class);
            one.setDataArray(expressContents);
            return one;
        }
    }

    /**
     * 条码识别进行快递查询
     *
     * @param fileUrl 快递图片
     */
    public String queryQrCodeReg(String fileUrl) throws ServiceException {
        //首先根据单号进行数据库查询
        try {
            String result = expressClient.qrCodeReg(fileUrl);
            log.info("条码识别的接口返回数据:" + result);
            JSONObject qrCode = JSON.parseObject(result);
            //如果是成功的
            if (qrCode.getIntValue("status") == 0) {
                JSONObject result1 = qrCode.getJSONArray("result").getJSONObject(0);
                return result1.getString("number");
            } else {
                throw new ServiceException(ErrorCode.QRCODE_QUERY_ERROR);
            }
        } catch (Exception e) {
            log.info("调用接口ExpressManager出现错误：" + e);
            e.printStackTrace();
            return "";
        }
    }
}

